package com.cupster.android_x_frame;

import android.content.Context;
import android.content.pm.PackageManager;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class DrawGestureActivity extends AppCompatActivity implements GestureOverlayView.OnGesturePerformedListener, GestureOverlayView.OnGesturingListener {

    GestureOverlayView mGestureOverlayView;
    TextView mTvHint;
    ConfirmDialog mDialog;

    GestureLibrary mGestureLibrary;
    File mFileGesture = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_gesture);
        mGestureOverlayView = findViewById(R.id.gesture_overlay);
        mTvHint = findViewById(R.id.text);

        mGestureOverlayView.setFadeOffset(800);//默认420ms,设置为1600ms
        mGestureOverlayView.setGestureStrokeType(GestureOverlayView.GESTURE_STROKE_TYPE_MULTIPLE);//默认单指连续绘制，设置为多指绘制
        mGestureOverlayView.setGestureStrokeWidth(10);//绘制线宽
        mGestureOverlayView.setGestureColor(Color.parseColor("#3ca1f9"));//绘制颜色
        mGestureOverlayView.setUncertainGestureColor(Color.parseColor("#a7dbf7"));//渐成色
        //设置监听
        mGestureOverlayView.addOnGesturePerformedListener(this);
        mGestureOverlayView.addOnGesturingListener(this);
        //设置手势-存储位置
        PermissionUtil.applyPermission(this ,101 ,BuildConfig.APPLICATION_ID);
    }

    @Override
    protected void onDestroy() {
        mGestureOverlayView.removeOnGesturePerformedListener(this);
        mGestureOverlayView.removeOnGesturingListener(this);
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 101:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initStoreFile();//外部存储方式
                } else {
                    Toast.makeText(this, "权限限制，可能无法正常使用主要功能", Toast.LENGTH_SHORT).show();
                    PermissionUtil.skipPermissionSetting(this);
                }
                break;
            default:
                break;
        }
    }

    private void initStoreFile() {
        if (mFileGesture == null && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            mFileGesture = new File(Environment.getExternalStorageDirectory(), "gesture");
        }
        if (mGestureLibrary == null) {
            mGestureLibrary = GestureLibraries.fromFile(mFileGesture);//方式1
//            mGestureLibrary = GestureLibraries.fromPrivateFile(this ,Environment.getExternalStorageDirectory()+"gesture");//方式2
//            mGestureLibrary = GestureLibraries.fromRawResource(this ,R.raw.gesture);//方式3
            mGestureLibrary.load();
        }
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //==============================================
    //=========GesturePerformedListener=============
    //==============================================
    @Override
    public void onGesturePerformed(GestureOverlayView gestureOverlayView, Gesture gesture) {
        mTvHint.append("\n");
        mTvHint.append("--> 所有绘制路径，识别完成");
        confirmGesture(gesture);
    }

    private void confirmGesture(final Gesture gesture) {
        if (mDialog != null && mDialog.isVisible()) {
            mDialog.dismiss();
            mDialog = null;
        }
        Bitmap bitmap = gesture.toBitmap(dp2px(this, 100), dp2px(this, 100), 10, Color.parseColor("#3ca1f9"));
        mDialog = ConfirmDialog.build("gesture", bitmap);
        mDialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = String.valueOf(view.getTag());
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(DrawGestureActivity.this, "请输入手势名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                initStoreFile();//校验，防止内存对象丢失->null

                mGestureLibrary.addGesture(name, gesture);
                mGestureLibrary.save();
            }
        });
        mDialog.show(getSupportFragmentManager(), "gesture_dialog");
    }
    //===============================================
    //=========GesturingListener=====================
    //===============================================
    @Override
    public void onGesturingStarted(GestureOverlayView gestureOverlayView) {
        mTvHint.append("\n");
        mTvHint.append("--> 单笔手势绘制开始");
    }

    @Override
    public void onGesturingEnded(GestureOverlayView gestureOverlayView) {
        mTvHint.append("\n");
        mTvHint.append("--> 单笔手势绘制结束");
    }
}